import time, requests, datetime, json
import nicegui as ui

SERVER = 'http://flocwise.cn'


def getAccessableDevice():
    api = '/getDeviceList?user_id=623576f170368a206e50c8ee'
    url = SERVER + api
    try:
        response = requests.post(url)
        if response.ok:
            res = json.loads(response.text)
            if res['Success']:
                deviceList = res['List']
                return True, deviceList
    except Exception as e:
        return False, []


def getDeviceStatus(SN):
    api = f'/s?SN={SN}'
    url = SERVER + api
    try:
        response = requests.post(url)
        if response.ok:
            res = json.loads(response.text)
            if res['Success']:
                status = res['Status']['Status']
                return True, status
    except Exception as e:
        return False, []

# getDeviceStatus('Floc024')

def getOnlineRate(SN,duration):
    api = f'/getOnlineRate?SN={SN}&duration={duration}'
    url = SERVER + api
    try:
        response = requests.post(url)
        if response.ok:
            res = json.loads(response.text)
            if res['Success']:
                return True, {
                    'time': res['disconnect_time'],
                    'duration': res['disconnection_duration'],
                    'longest': json.loads(res['longest'])['duration']
                }
        return False, response.text
    except Exception as e:
        return False, str(e) + response.text

# getDeviceStatus('Floc024')